use termion::event::Key;

#[derive(PartialEq)]
pub enum OpKind {
    Add,
    Delete,
    Backspace,
}

pub struct Edit {
    pub kind: OpKind,
    pub content: char,
}

impl Edit {
    pub fn new(key: &Key, content: Option<char>) -> Self {
        let op = match key {
            Key::Char(_c) => OpKind::Add,
            Key::Backspace => OpKind::Backspace,
            Key::Delete => OpKind::Delete,
            _ => unreachable!(),
        };
        let content = if let Some(c) = content {
            c
        } else {
            char::default()
        };

        Self {
            kind: op,
            content,
        }
    }
}

pub struct History {
    edits: Vec<Edit>,
    index: usize,
}

impl History {
    pub fn new() -> Self {
        Self {
            edits: Vec::new(),
            index: 0,
        }
    }

    pub fn push_edit(&mut self, edit: Edit) {
        self.edits.truncate(self.index);
        self.edits.push(edit);
        self.index += 1;
    }

    pub fn undo(&mut self) -> Option<&Edit> {
        if self.index > 0 {
            self.index -= 1;
            Some(&self.edits[self.index])
        } else {
            None
        }
    }

    pub fn redo(&mut self) -> Option<&Edit> {
        if self.index < self.edits.len() {
            let edit = &self.edits[self.index];
            self.index += 1;
            Some(edit)
        } else {
            None
        }
    }

    pub fn unmodified(&self) -> bool {
        self.index == 0
    }
}
